<template>
  <view class="my-page">
    <!-- 用户信息卡片 -->
    <view class="user-card" @click="handleUserInfoClick">
      <view class="user-avatar" :class="{ 'placeholder': !userStore.userInfo.avatar }">
        <image v-if="userStore.userInfo.avatar" :src="userStore.userInfo.avatar" mode="aspectFill"></image>
        <view v-else class="avatar-placeholder">
          <up-icon customPrefix="iconfont" name="niming" size="40" color="#cccccc" ></up-icon>
        </view>
      </view>
      
      <view class="user-info">
        <view class="user-main-info">
          <text class="user-name">{{ userStore.userInfo.nickname || '未登录' }}</text>
          <u-badge v-if="userStore.userInfo.is_vip" :text="'VIP'" type="success" size="mini" style="margin-left: 8px;"></u-badge>
        </view>
        <text class="user-id">ID: {{ userStore.userInfo.id || '--' }}</text>
      </view>
      <up-icon name="arrow-right" size="32" color="#cccccc" ></up-icon>

    </view>
    
    <!-- 积分展示 -->
    <points-display 
      :points="userStore.userInfo.points || 0"
      :monthly-income="monthlyIncome"
      :monthly-expense="monthlyExpense"
      :records="pointsRecords"
      :show-records="false"
      :show-rules="false"
      :expandable="false"
      @view-records="navigateToPointsRecords"
      @view-leaderboard="navigateToLeaderboard"
    />
    
    <!-- 任务统计 -->
    <view class="task-stats">
      <view class="stat-item" @click="navigateToTaskList('all')">
        <text class="stat-number">{{ taskStats.total || 0 }}</text>
        <text class="stat-label">全部任务</text>
      </view>
      
      <view class="stat-divider"></view>
      
      <view class="stat-item" @click="navigateToTaskList('in_progress')">
        <text class="stat-number">{{ taskStats.inProgress || 0 }}</text>
        <text class="stat-label">进行中</text>
      </view>
      
      <view class="stat-divider"></view>
      
      <view class="stat-item" @click="navigateToTaskList('underReview')">
        <text class="stat-number">{{ taskStats.completed || 0 }}</text>
        <text class="stat-label">待审核</text>
      </view>
	  
	  <view class="stat-divider"></view>
	  
	  <view class="stat-item" @click="navigateToTaskList('completed')">
	    <text class="stat-number">{{ taskStats.completed || 0 }}</text>
	    <text class="stat-label">已完成</text>
	  </view>
    </view>
    
    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-title">
        <text>任务中心</text>
      </view>
      
      <view class="menu-grid">
        <view class="menu-item" @click="navigateToTaskList('pending')">
          <view class="menu-icon new-task">
            <up-icon customPrefix="iconfont" name="xinshou" size="28" color="#cccccc" ></up-icon>
          </view>
          <text class="menu-text">新手任务</text>
        </view>
        
        <view class="menu-item" @click="navigateToTaskList('daily')">
          <view class="menu-icon daily-task">
            <up-icon name="calendar" size="28" color="#67c23a" />
          </view>
          <text class="menu-text">每日任务</text>
        </view>
        
        <view class="menu-item" @click="navigateToTaskList('share')">
          <view class="menu-icon share-task">
            <up-icon name="share" size="28" color="#e6a23c" />
          </view>
          <text class="menu-text">分享任务</text>
        </view>
        
        <view class="menu-item" @click="navigateToTaskList('survey')">
          <view class="menu-icon survey-task">
            <up-icon customPrefix="iconfont" name="wenjuantiaocha" size="24" color="#f56c6c" ></up-icon>
          </view>
          <text class="menu-text">调查任务</text>
        </view>
      </view>
    </view>
    
    <!-- 设置菜单 -->
    <view class="menu-section">
      <view class="menu-group">
        <view class="menu-row" @click="navigateToPointsRecords">
          <view class="menu-row-left">
            <up-icon customPrefix="iconfont" name="jinbi" size="24" color="#ff9500" ></up-icon>
            <text class="menu-row-text">积分明细</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
        
        <view class="menu-row" @click="navigateToLeaderboard">
          <view class="menu-row-left">
            <up-icon customPrefix="iconfont" name="paihangbang" size="24" color="#ff9500" ></up-icon>
            <text class="menu-row-text">积分排行榜</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
        
        <view class="menu-row" @click="navigateToRewardCenter">
          <view class="menu-row-left">
            <u-icon name="gift" size="24" color="#48dbfb" />
            <text class="menu-row-text">奖励中心</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
      </view>
<!--      <view class="menu-group">
        <view class="menu-row" @click="navigateToSettings">
          <view class="menu-row-left">
            <u-icon name="setting" size="24" color="#90a4ae" />
            <text class="menu-row-text">设置</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
        
        <view class="menu-row" @click="navigateToHelp">
          <view class="menu-row-left">
            <u-icon name="question-circle" size="24" color="#786fa6" />
            <text class="menu-row-text">帮助与反馈</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
        
        <view class="menu-row" @click="navigateToAbout">
          <view class="menu-row-left">
            <up-icon customPrefix="iconfont" name="aboutus" size="24" color="#ff9500" ></up-icon>
            <text class="menu-row-text">关于我们</text>
          </view>
          <u-icon name="arrow-right" size="18" color="#cccccc" />
        </view>
      </view> -->
    </view>
    
    <!-- 退出登录按钮 -->
    <u-button 
      v-if="userStore.isLoggedIn" 
      type="default" 
      size="large"
      :plain="true"
      @click="handleLogout"
      style="margin-top: 32px; margin-bottom: 20px;"
    >
      退出登录
    </u-button>
    
    <!-- 登录弹窗 -->
    <login-modal 
      v-model:visible="showLoginModal" 
      @loginSuccess="handleLoginSuccess"
    ></login-modal>
    
    <!-- 确认弹窗 -->
    <u-modal 
      v-model:show="showConfirmModal" 
      :content="confirmContent"
      :show-cancel-button="true"
      confirm-text="确认"
      cancel-text="取消"
      @confirm="handleConfirm"
    ></u-modal>
    
    <!-- 加载中 -->
    <u-loading-page v-if="loading" color="#409eff"></u-loading-page>
  </view>
</template>

<script>
import { defineComponent, ref, reactive, onMounted, computed } from 'vue';
import { useUserStore } from '../../store/user.js';
import { useTaskStore } from '../../store/task.js';
import { usePointsStore } from '../../store/points.js';
import PointsDisplay from '../../components/points-display.vue';
import LoginModal from '../../components/login-modal.vue';

export default defineComponent({
  name: 'MyPage',
  components: {
    PointsDisplay,
    LoginModal
  },
  setup() {
    const userStore = useUserStore();
    const taskStore = useTaskStore();
    const pointsStore = usePointsStore();
    
    // 状态管理
    const loading = ref(false);
    const showLoginModal = ref(false);
    const showConfirmModal = ref(false);
    const confirmContent = ref('');
    const confirmAction = ref('');
    
    // 模拟数据
    const monthlyIncome = ref(250);
    const monthlyExpense = ref(80);
    const pointsRecords = ref([
      {
        id: 1,
        points: 50,
        type: 'income',
        source: 'task_complete',
        description: '完成新手任务',
        created_at: Date.now() - 86400000
      },
      {
        id: 2,
        points: 20,
        type: 'income',
        source: 'daily_sign',
        description: '每日签到',
        created_at: Date.now() - 172800000
      },
      {
        id: 3,
        points: 100,
        type: 'expense',
        source: 'reward_exchange',
        description: '兑换奖励',
        created_at: Date.now() - 259200000
      }
    ]);
    
    // 任务统计数据
    const taskStats = reactive({
      total: 0,
      inProgress: 0,
      completed: 0
    });
    
    // 加载用户数据
    const loadUserData = async () => {
      if (!userStore.isLoggedIn) return;
      
      try {
        loading.value = true;
        
        // 加载用户信息
        await userStore.fetchUserInfo();
        
        // 加载任务统计
        await loadTaskStats();
        
        // 加载积分记录
        await loadPointsRecords();
      } catch (error) {
        console.error('加载用户数据失败:', error);
      } finally {
        loading.value = false;
      }
    };
    
    // 加载任务统计
    const loadTaskStats = async () => {
      try {
        const result = await taskStore.fetchUserTaskStats();
        if (result && result.data) {
          taskStats.total = result.data.total || 0;
          taskStats.inProgress = result.data.inProgress || 0;
          taskStats.completed = result.data.completed || 0;
        }
      } catch (error) {
        console.error('加载任务统计失败:', error);
        // 使用模拟数据
        taskStats.total = 12;
        taskStats.inProgress = 3;
        taskStats.completed = 9;
      }
    };
    
    // 加载积分记录
    const loadPointsRecords = async () => {
      try {
        const result = await pointsStore.fetchPointsRecords({ page: 1, pageSize: 3 });
        if (result && result.data && result.data.length > 0) {
          pointsRecords.value = result.data;
        }
      } catch (error) {
        console.error('加载积分记录失败:', error);
      }
    };
    
    // 处理用户信息点击
    const handleUserInfoClick = () => {
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
      } else {
        // 跳转到用户详情页
        // uni.navigateTo({ url: '/pages/user-detail/user-detail' });
        showToast('跳转到用户详情页');
      }
    };
    
    // 处理登录成功
    const handleLoginSuccess = () => {
      showLoginModal.value = false;
      loadUserData();
    };
    
    // 处理退出登录
    const handleLogout = () => {
      confirmContent.value = '确定要退出登录吗？';
      confirmAction.value = 'logout';
      showConfirmModal.value = true;
    };
    
    // 处理确认操作
    const handleConfirm = async () => {
      if (confirmAction.value === 'logout') {
        try {
          await userStore.logout();
          showToast('退出登录成功');
          // 重置数据
          taskStats.total = 0;
          taskStats.inProgress = 0;
          taskStats.completed = 0;
          pointsRecords.value = [];
        } catch (error) {
          console.error('退出登录失败:', error);
          showToast('退出登录失败');
        }
      }
      showConfirmModal.value = false;
      confirmAction.value = '';
    };
    
    // 导航到任务列表
    const navigateToTaskList = (type = 'all') => {
      if (!userStore.isLoggedIn && type !== 'all') {
        showLoginModal.value = true;
        return;
      }
      
      uni.navigateTo({
        url: `/pages/task-list/task-list?type=${type}`
      });
    };
    
    // 导航到积分明细
    const navigateToPointsRecords = () => {
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      // uni.navigateTo({ url: '/pages/points-records/points-records' });
      showToast('跳转到积分明细页');
    };
    
    // 导航到积分排行榜
    const navigateToLeaderboard = () => {
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      // uni.navigateTo({ url: '/pages/leaderboard/leaderboard' });
      showToast('跳转到积分排行榜');
    };
    
    // 导航到奖励中心
    const navigateToRewardCenter = () => {
      if (!userStore.isLoggedIn) {
        showLoginModal.value = true;
        return;
      }
      
      // uni.navigateTo({ url: '/pages/reward-center/reward-center' });
      showToast('跳转到奖励中心');
    };
    
    // 导航到设置
    const navigateToSettings = () => {
      // uni.navigateTo({ url: '/pages/settings/settings' });
      showToast('跳转到设置页');
    };
    
    // 导航到帮助
    const navigateToHelp = () => {
      // uni.navigateTo({ url: '/pages/help/help' });
      showToast('跳转到帮助与反馈');
    };
    
    // 导航到关于
    const navigateToAbout = () => {
      // uni.navigateTo({ url: '/pages/about/about' });
      showToast('跳转到关于我们');
    };
    
    // 简易提示
    const showToast = (title) => {
      uni.showToast({
        title: title,
        icon: 'none',
        duration: 1500
      });
    };
    
    // 生命周期
    onMounted(() => {
      // 页面显示时加载数据
      loadUserData();
      
      // 监听页面显示事件
      uni.$on('pageShow', loadUserData);
    });
    
    return {
      userStore,
      loading,
      showLoginModal,
      showConfirmModal,
      confirmContent,
      monthlyIncome,
      monthlyExpense,
      pointsRecords,
      taskStats,
      handleUserInfoClick,
      handleLoginSuccess,
      handleLogout,
      handleConfirm,
      navigateToTaskList,
      navigateToPointsRecords,
      navigateToLeaderboard,
      navigateToRewardCenter,
      navigateToSettings,
      navigateToHelp,
      navigateToAbout
    };
  }
});
</script>

<style lang="scss" scoped>
.my-page {
  padding: 16px;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.user-card {
  display: flex;
  align-items: center;
  background: linear-gradient(180deg, #5badff 0%, #45b40e 100%);
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 16px;
  color: #ffffff;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  cursor: pointer;
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
  
  .user-avatar {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background-color: #ffffff;
    overflow: hidden;
    margin-right: 16px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    
    &.placeholder {
      background-color: rgba(255, 255, 255, 0.2);
    }
    
    image {
      width: 100%;
      height: 100%;
    }
    
    .avatar-placeholder {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  
  .user-info {
    flex: 1;
  }
  
  .user-main-info {
    display: flex;
    align-items: center;
    margin-bottom: 4px;
  }
  
  .user-name {
    font-size: 18px;
    font-weight: 600;
    margin-right: 8px;
  }
  
  .user-id {
    font-size: 13px;
    opacity: 0.9;
  }
}

.task-stats {
  display: flex;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .stat-item {
    flex: 1;
    text-align: center;
    cursor: pointer;
    
    &:active {
      opacity: 0.7;
    }
    
    .stat-number {
      display: block;
      font-size: 24px;
      font-weight: 700;
      color: #333333;
      margin-bottom: 4px;
    }
    
    .stat-label {
      display: block;
      font-size: 14px;
      color: #666666;
    }
  }
  
  .stat-divider {
    width: 1px;
    background-color: #f0f0f0;
  }
}

.menu-section {
  margin-bottom: 20px;
}

.menu-title {
  margin-bottom: 12px;
  padding-left: 4px;
  
  text {
    font-size: 16px;
    font-weight: 600;
    color: #333333;
  }
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  background-color: #ffffff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .menu-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    
    &:active {
      opacity: 0.7;
    }
    
    .menu-icon {
      width: 56px;
      height: 56px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 8px;
      background-color: #f5f5f5;
      
      &.new-task {
        background-color: #ecf5ff;
      }
      
      &.daily-task {
        background-color: #f0f9eb;
      }
      
      &.share-task {
        background-color: #fdf6ec;
      }
      
      &.survey-task {
        background-color: #fef0f0;
      }
    }
    
    .menu-text {
      font-size: 13px;
      color: #666666;
    }
  }
}

.menu-group {
  background-color: #ffffff;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  
  .menu-row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16px;
    border-bottom: 1px solid #f5f5f5;
    cursor: pointer;
    
    &:last-child {
      border-bottom: none;
    }
    
    &:active {
      background-color: #f9f9f9;
    }
    
    .menu-row-left {
      display: flex;
      align-items: center;
    }
    
    .menu-row-text {
      font-size: 15px;
      color: #333333;
      margin-left: 12px;
    }
  }
}

// 响应式适配
@media screen and (min-width: 768px) {
  .my-page {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
  }
  
  .menu-grid {
    gap: 20px;
    padding: 24px;
  }
}

// 深色模式适配
:global(.dark-theme) .my-page {
  background-color: #1a1a1a;
  
  .user-card {
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
  }
  
  .task-stats {
    background-color: #2a2a2a;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    
    .stat-divider {
      background-color: #333333;
    }
    
    .stat-number {
      color: #ffffff;
    }
    
    .stat-label {
      color: #999999;
    }
  }
  
  .menu-title {
    text {
      color: #ffffff;
    }
  }
  
  .menu-grid {
    background-color: #2a2a2a;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    
    .menu-icon {
      background-color: #3a3a3a;
      
      &.new-task {
        background-color: #1e2b3c;
      }
      
      &.daily-task {
        background-color: #1e3c2a;
      }
      
      &.share-task {
        background-color: #3c331e;
      }
      
      &.survey-task {
        background-color: #3c1e1e;
      }
    }
    
    .menu-text {
      color: #999999;
    }
  }
  
  .menu-group {
    background-color: #2a2a2a;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    
    .menu-row {
      border-bottom-color: #333333;
      
      &:active {
        background-color: #3a3a3a;
      }
      
      .menu-row-text {
        color: #ffffff;
      }
    }
  }
}
</style>